Tack.Designer.ActionBlock = new Class({
	initialize: function (designer, ab) {
		this.html = {
			main: new Element('li', { 'class': 'action-block' }),
			header: new Element('ul', { 'class': 'header' }),
			menu: new Element('li', { 'class': 'menu' }),
			actions: new Element('ol', { 'class': 'actions' })
		};

		this.html.header.adopt(this.html.menu);
		this.html.main.adopt(this.html.header, this.html.actions);

		this.designer = designer;
		this.actionBlock = ab;
		this.conditions = [];
		this.actions = [];

		ab.conditions.each(function (condition) {
			this.addCondition(condition);
		}, this);

		ab.actions.each(function (action) {
			this.addAction(action);
		}, this);

		if (ab.elseBlock) {
			this.elseBlock = new Tack.Designer.ActionBlock(designer, ab.elseBlock);

			this.elseBlock.html.main.addClass('else');
			this.html.actions.adopt(this.elseBlock.html.main);
		} else {
			this.elseBlock = null;
		}

		designer.actionBlockMenu.attach(this.html.menu, this);
	},

	addAction: function (action) {
		var da;
		if (action instanceof Tack.ActionBlock) {
			da = new Tack.Designer.ActionBlock(this.designer, action);
		} else {
			da = new Tack.Designer.Action(this.designer, action);
		}

		this.actions.push(da);

		if (this.elseBlock)
			da.html.main.inject(this.elseBlock.html.main, 'before');
		else
			this.html.actions.adopt(da.html.main);
	},

	addCondition: function (condition) {
		var dc = new Tack.Designer.Condition(this.designer, condition);

		this.conditions.push(dc);
		this.html.header.adopt(dc.html.main);
	},

	newAction: function (type) {
		var action = new type();

		this.actionBlock.addAction(action);
		this.addAction(action);
	},

	newCondition: function (type) {
		var condition = new type();

		this.actionBlock.addCondition(condition);
		this.addCondition(condition);
	},
	
	newElseBlock: function () {
		if (this.actionBlock.elseBlock) {
			this.elseBlock.newElseBlock();
			return;
		}

		var ab = new Tack.ActionBlock();
		this.actionBlock.setElseBlock(ab);

		this.elseBlock = new Tack.Designer.ActionBlock(this.designer, ab);
		this.elseBlock.html.main.addClass('else');
		this.html.actions.adopt(this.elseBlock.html.main);
	},

	remove: function () {
		if (!this.actionBlock.actionBlock) {
			alert('You can\'t remove a top-level action block.');
			return;
		}

		this.actionBlock.remove();
		this.html.main.destroy();
	}
});
